import { useCounterStore } from "@/stores/counter"
import axios from "axios"

axios.defaults.baseURL="http://localhost:8080"

export function doGet(url,params){
   return axios({
        method:"GET",
        url:url,
        params:params,
        dataType:"json"
    })
}

export function doPost(url,data,headers={}){
    return axios({
        headers:headers,
        method:"POST",
        url:url,
        data:data,
        dataType:"json",
    })
}

export function doPut(url,data){
    return axios({
        method:"PUT",
        url:url,
        data:data,
        dataType:"json"
    })
}

export function doDelete(url,params){
    return axios({
        method:"DELETE",
        url:url,
        params:params,
        dataType:"json"
    })
}
import { ElMessageBox } from 'element-plus'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    let token=window.sessionStorage.getItem("token")
    if(!token){
        token=window.localStorage.getItem("token")
        if(token){
            config.headers.remember=true
        }
    }
    config.headers.Authorization=token
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    let store=useCounterStore()
    if(error.response.data.code==400&&error.response.data.message.includes("Token")){
        ElMessageBox.alert(error.response.data.message, '警告', {
            confirmButtonText: '确定',
            callback: (action) => {
                store.changestatusForFalse()
                window.localStorage.removeItem("token")
                window.sessionStorage.removeItem("token")
                window.location.replace('/');
            },
          })
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  });